import { endpoint } from '/utils/util.js';
App({
  onLaunch: function () {
		this.getUserInfo();
		this.getDailyFreeParseNum();
		this.getTotalParseNum();
  },

  /**
   * 登陆并获取用户信息、token
   * @param {*} callback 
   */
  getUserInfo: function (callback = null) {
    // 登录
    wx.login({
      success: res => {
        console.log(res)
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        var code = res.code;
        wx.getUserInfo({
          success: res => {
            console.log('app/getUserInfo')
            console.log(res)
            // 可以将 res 发送给后台解码出 unionId
            if (!this.checkIsLogin()){
              this.getToken(code, res.encryptedData, res.iv);
            }
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            callback && callback(res);
          }
        })

      }
    });
  },

  globalData: {
    userInfo: null,
    hasUserInfo: false,
    defaultDailyFreeParseNum: 100,
    dailyFreeParseNum : '--',
    totalParseNum : '--',
    pic_url : null,
  },

  //全局统一调用接口的方法
  apiRequest: function (options) {
    wx.request({
      url: endpoint.apiDomain + options.url,
      method: options.method ? options.method : 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'Accept': 'application/json',
      },
      dataType: 'json',
      data: options.data,
      success: res => {
        switch (res.statusCode) {
          case 200:
            options.success(res);
            break;
          case 401:
            console.log('401登陆中....')
            this.toLogin();
            break;
          case 422:
            break;
          case 404:
            wx.showToast({
              title: '请求地址不存在',
              icon: 'none'
            })
            break;
          default:
            wx.showToast({
              title: '出错了～请稍后再试',
              icon: 'none'
            })
        }
      },
      fail: res => {
        if (options.fail) {
          options.fail(res);
        }
      },
      complete: res => {
        if (options.complete) {
          options.complete(res);
        }
      }
    });
  },

  /**
   * 验证登录
   */
  checkIsLogin(autoLogin = false) {
    if (wx.getStorageSync('token')) {
      return true;
    }
    if (autoLogin) {
      console.log('自动登录')
      this.getUserInfo();
    } else {
      return false;
    }
  },

  /**
   * 跳转登陆页
   */
  toLogin() {
    this.globalData.hasUserInfo = false;
    this.globalData.userInfo = {};
    wx.removeStorageSync('token');
    wx.removeStorageSync('userInfo');
    wx.showToast({
      title: '跳转登陆中...',
      icon: 'none',
      success: res => {
        wx.switchTab({
          url: '/pages/mine/mine'
        })
      }
    })
  },

  /**
   * 获取token
   */
  getToken(code, encryptedData, iv, callback = null) {
    var that = this;
    //调后端接口获取token
    this.apiRequest({
      url: '/auth/login',
      method: 'POST',
      data: {
        'code': code,
        'data': encryptedData,
        'iv': iv
      },
      success: res => {
        if (!res.data.openid){
          console.log('服务器登录失败')
          return false;
        }

        console.log('getTokend登录')
        console.log(res.data)

        this.globalData.userInfo = res.data
        wx.setStorageSync('userInfo', res.data);

        console.log('设置token')
        console.log(res.data.token)

        wx.setStorageSync('token', res.data.token);
        callback && callback();
      }
    });
	},
	 /**
     * 获取当日免费次数
     * 使用本地存储，不走服务端
     */
  getDailyFreeParseNum() {
			this.apiRequest({
				url: endpoint.getFreeNum,
				success: res => {
					wx.setStorageSync('dailyFreeParseNum', res.data);
					this.globalData.dailyFreeParseNum = res.data
				}
			})
	},

	/**
	 * 获取总解析次数
	 */
	getTotalParseNum() {
		this.apiRequest({
			url: endpoint.getTotalParseNum,
			success: res => {
				wx.setStorageSync('totalParseNum', res.data.total_num);
				this.globalData.totalParseNum = res.data.total_num
			}
		})
	},

});